package com.snmp.smn.monitors;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.snmp.smn.beans.Agent;
import com.snmp.smn.db.DBHelper;
import com.snmp.smn.pdu.PDUFactory;
import com.snmp.smn.utils.EmailSender;
import com.snmp.smn.utils.Utilities;

public class AgentMonitor {

	private Agent agent;
	
	public AgentMonitor(Agent agent) {
		this.agent = agent;
	}
	
	public void checkHeartBeat() throws Exception {
		Utilities.log("Checking heart beat for " + agent);
		
		try {
			Socket socket = new Socket(agent.getAgentIP(), agent.getAgentPort());
			OutputStream os = socket.getOutputStream();
			os.write(PDUFactory.createHeartBeatRequestPDU());
			
			InputStream is = socket.getInputStream();
			byte[] b = new byte[1024];
			is.read(b);
			
			Utilities.log("Response for heart beat received for " + agent);
			
			String response = new String(b).trim();
			updateSuccessfulActivity(response);
			
			socket.close();
		} catch (Exception e) {
			Utilities.log("Could not check heart beat for " + agent);
			
			updateFailedActivity();
			
			EmailSender.sendAgentFailed(agent.getAgentId(), agent.getAgentName(), 
											agent.getAgentIP(), agent.getAgentPort(),
												e.getMessage());
		}
	}

	private void updateSuccessfulActivity(String response) throws Exception {
		String username = Utilities.getUserName(response);
		
		DBHelper.insertSuccessfulActivity(agent.getAgentId(), username);
		
		DBHelper.updateSuccessfulAgentStatus(agent.getAgentId());
	}
	
	private void updateFailedActivity() throws Exception {
		DBHelper.insertFailedActivity(agent.getAgentId());
		
		DBHelper.updateFailedAgentStatus(agent.getAgentId());
	}
}
